
import 'dart:collection';
import 'package:flutter/material.dart';

class YKNavigatorObserverConfig {

  void Function(String msg)? debugLogCallBack;

  Route<dynamic>? _curRoute;

  Queue<Route<dynamic>> _routeQueue = DoubleLinkedQueue();
  
  static YKNavigatorObserverConfig? _instance_;

  static YKNavigatorObserverConfig get instance {
    _instance_ ??= YKNavigatorObserverConfig._();
    return _instance_!;
  }

  Route<dynamic>? get curRoute => _curRoute;

  Queue<Route<dynamic>> get routeQueue => _routeQueue;

  YKNavigatorObserverConfig._();

  void _push(Route<dynamic> route, Route<dynamic>? previousRoute) {
    _routeQueue.add(route);
    debugLogCallBack?.call("YKNavigatorObserver push $route}");
  }

  void _replace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    _routeQueue.remove(oldRoute);
    if (newRoute != null) {
      routeQueue.add(newRoute);
    }
    debugLogCallBack?.call("YKNavigatorObserver replace $newRoute}");
  }

  void _pop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (_routeQueue.isEmpty) return;
    _routeQueue.remove(route);
    debugLogCallBack?.call("YKNavigatorObserver pop $route}");
  }

  void _remove(Route<dynamic> route) {
    if (_routeQueue.isEmpty) return;
    _routeQueue.remove(route);
    debugLogCallBack?.call("YKNavigatorObserver remove $route}");
  }
}

class YKNavigatorObserver extends NavigatorObserver {

  @override
  void didPop(Route route, Route? previousRoute) {
    YKNavigatorObserverConfig.instance._curRoute = previousRoute;
    YKNavigatorObserverConfig.instance._pop(route, previousRoute);
    super.didPop(route, previousRoute);
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    YKNavigatorObserverConfig.instance._curRoute = route;
    YKNavigatorObserverConfig.instance._push(route, previousRoute);
    super.didPush(route, previousRoute);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    YKNavigatorObserverConfig.instance._curRoute = newRoute;
    YKNavigatorObserverConfig.instance._replace(newRoute: newRoute, oldRoute: oldRoute);
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    YKNavigatorObserverConfig.instance._remove(route);
    super.didRemove(route, previousRoute);
  }

  @override
  void didStartUserGesture(Route route, Route? previousRoute) {
    super.didStartUserGesture(route, previousRoute);
  }

  @override
  void didStopUserGesture() {
    super.didStopUserGesture();
  }

}